package fun.tan90.easy.binlog.manager.config;

import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.keygen.KeyGenerators;
import com.mybatisflex.core.tenant.TenantFactory;
import com.mybatisflex.core.tenant.TenantManager;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;
import fun.tan90.easy.binlog.base.convention.enums.LogicDelete;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

/**
 * description TODO
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/6/28 13:28
 */
@Slf4j
@Configuration
@MapperScan("fun.tan90.easy.binlog.manager.dataobject.mapper")
public class MybatisFlexAutoConfiguration implements MyBatisFlexCustomizer {

    @Override
    public void customize(FlexGlobalConfig globalConfig) {
        globalConfig.setLogicDeleteColumn("logical_delete");
        //设置数据库正常时的值
        globalConfig.setNormalValueOfLogicDelete(LogicDelete.NORMAL.getValue());
        //设置数据已被删除时的值
        globalConfig.setDeletedValueOfLogicDelete(LogicDelete.DELETE.getValue());
        //全局配置多租户字段
        globalConfig.setTenantColumn("tenant_id");
        //全局配置乐观锁字段
        globalConfig.setVersionColumn("version");

        // 需要定义在认证模块
        TenantManager.setTenantFactory(new TenantFactory() {
            @Override
            public Object[] getTenantIds() {
                //TODO
                //通过这里返回当前租户 ID
                return new Object[]{100};
            }
        });

        FlexGlobalConfig.KeyConfig keyConfig = new FlexGlobalConfig.KeyConfig();
        keyConfig.setKeyType(KeyType.Generator);
        keyConfig.setValue(KeyGenerators.snowFlakeId);
        globalConfig.setKeyConfig(keyConfig);

        AuditManager.setAuditEnable(true);
        AuditManager.setMessageCollector(message -> log.debug("{} ms >>> {}", message.getElapsedTime(), message.getFullSql()));
    }

}